package com.xian.client;


import com.xian.hander.UserClientHandler;
import com.xian.service.RpcRequest;
import com.xian.util.JSONSerializer;
import com.xian.util.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPC_Consumer {

    //1.创建一个线程池对象，它要处理自定义对象事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.生命自定义事件处理器，UserClientHandler
    private static UserClientHandler userClientHandler;


    //3.初始化客户端
    public  static void initClient() throws InterruptedException {
        //1初始化userClientHandler
        userClientHandler = new UserClientHandler();
        //创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //穿件客户端引导对象
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //自定义一个channleHandel 添加到同道中
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1", 8999).sync();
    }
    //4.编写一个方法，使用jdk的动态代理 创建对象
    public static  Object createProxy(final Class<?> serviceClass, final String className,final String methodName){
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //（1）调用初始化netty客户端的方法

                        if(userClientHandler == null){
                            initClient();
                        }

                        // 设置参数
                        RpcRequest req = new RpcRequest();
                        //className必须与服务端中的实现类在ioc容器内的名称完全一致，否则会找不到实现类对象
                        req.setClassName(className);
                        //使用灵活判断途径时，方法名和方法传参类型列表都必须完全一致
                        req.setMethodName(methodName);
                        Class<?>[] clazz = {String.class};
                        req.setParameterTypes(clazz);
                        //实际传参
                        req.setParameters(args);
                        //userClientHandler.setPara(providerName+args[0]);
                        userClientHandler.setPara(req);
                        // 去服务端请求数据
                        return executorService.submit(userClientHandler).get();
                    }
                }
        );
    }
}
